package org.springframework.samples.petclinic.controllers.EnterControls;



import jakarta.servlet.http.HttpSession;
import org.springframework.samples.petclinic.model.administrator.AdminRepository;
import org.springframework.samples.petclinic.system.ClientType;
import org.springframework.samples.petclinic.system.WebSecurityConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AdminLoginController {

	private final AdminRepository adminRepository;
	AdminLoginController(AdminRepository adminRepository){this.adminRepository=adminRepository;}
//	@GetMapping("/")
//	public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account, Model model) {
//		model.addAttribute("name", account);
//		return "index";
//	}

	@GetMapping("/adminLogin")
	public String adminlogin() {
		return "adminLogin";
	}

	@PostMapping("/adminLoginPost")
	public String loginPost(@RequestParam(value = "name") String username, @RequestParam(value = "password") String password, HttpSession session) {

		String shouldBePassword = adminRepository.findPassword(username);
		if (!password.equals(shouldBePassword)) {//验证密码

			return "adminLogin";
		}

		// 设置session
		session.setAttribute(WebSecurityConfig.SESSION_KEY, username);
		session.setAttribute(WebSecurityConfig.TYPE, ClientType.ADMIN_TYPE);

		return "redirect:/home";
	}

	@GetMapping("/logout")
	public String logout(HttpSession session) {
		// 移除session
		session.removeAttribute(WebSecurityConfig.SESSION_KEY);
		session.removeAttribute("TYPE");
		return "/entrance";
	}

}
